//app.js
import ports from './utils/ports.js';
import base from './utils/base.js';
import https from './utils/https.js';
import './utils/text-decoder-polyfill';
const MarkdownIt = require('markdown-it');


// import details from './pages/details/details';
App({
  onLaunch: function () {


    const that = this;
    // 获取手机信息
    wx.getSystemInfo({
      success: function (res) {
        that.globalData.system = {
          barH: res.statusBarHeight,
          ratio: res.screenWidth / 750,
          version: res.version,
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight,
          screenWidth: res.screenWidth,
          screenHeight: res.screenHeight,
        }
      },
    })
    wx.getSystemInfoSync({
      success(res) {
        console.log(res)
      }
    })
    //管理更新
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      if (res.hasUpdate) {
        updateManager.onUpdateReady(function () {
          wx.showModal({
            title: '更新提示',
            content: '新版本已经准备好，是否重启应用？',
            success: function (res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate()
              }
            }
          })
        })
      }
    })
    wx.checkSession({
      success() {
        console.log('登录未失效');
        // 检查是否有openid，如果没有则重新登录
        const openid = wx.getStorageSync('openid');
        if (!openid) {
          that.login();
        }
      },
      fail() {
        // session_key 已经失效，需要重新执行登录流程
        console.log('登录过期，重新登录');
        that.login();
      }
    })
  },
  timeFormat(timedata, type, hms, ymdhm, today) {
    // return timedata;
    var that = this
    if (!timedata) {
      return
    }
    timedata = timedata.substr(0, 19).replace(/-/g, "/").replace(/T/g, ' ')
    var date = new Date(timedata.substr(0, 19));
    var Year = date.getFullYear();
    var Month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var d = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var Hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var Minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var Seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    var over_time = Year + "/" + Month + "/" + d + " " + Hours + ":" + Minutes + ":" + Seconds
    var time = new Date(Date.parse(over_time));
    time.setTime(time.setHours(time.getHours()));
    var Y = time.getFullYear() + '/';
    var M = that.addZero(time.getMonth() + 1) + '/';
    var D = that.addZero(time.getDate()) + ' ';
    var h = that.addZero(time.getHours()) + ':';
    var m = that.addZero(time.getMinutes());
    var s = ':' + that.addZero(time.getSeconds());

    if (type === true) {
      return (Y + M + D + " " + h + m + s);
    } else if (hms === true) {
      return (h + m + s)
    } else if (ymdhm === true) {
      return (Y + M + D + " " + h + m);
    } else if (today === true) {
      return (M + D)
    } else {
      return (Y + M + D)
    }
  },
  //不足10 补0操作
  addZero(num) {
    return num < 10 ? '0' + num : num;
  },
  ReverseRankingDate(data, p) { //倒序时间排序
    for (var i = 0; i < data.length - 1; i++) {
      for (var j = 0; j < data.length - 1 - i; j++) {
        // console.log(Date.parse(data[j][p]));
        if (Date.parse(data[j][p]) < Date.parse(data[j + 1][p])) {
          var temp = data[j];
          data[j] = data[j + 1];
          data[j + 1] = temp;
        }
      }
    }
    return data;
  },
  ForwardRankingDate(data, p) { //正序时间排序
    for (var i = 0; i < data.length - 1; i++) {
      for (var j = 0; j < data.length - 1 - i; j++) {
        console.log(Date.parse(data[j][p]));
        if (Date.parse(data[j][p]) > Date.parse(data[j + 1][p])) {
          var temp = data[j];
          data[j] = data[j + 1];
          data[j + 1] = temp;
        }
      }
    }
    return data;
  },
  login() {
    var that = this;
    // 登录
    wx.login({
      success: info => {
        console.log('微信登录成功，code:', info.code);
        var data = {
          appid: that.globalData.appid,
          code: info.code
        }
        getApp().ports.api21({
          data: data
        }).then((res) => {
          console.log('登录接口调用成功:', res);
          if (res.data) {
            wx.setStorageSync('access', res.data.access);
            wx.setStorageSync('refresh', res.data.refresh);
            // 确保openid存在且不为空
            if (res.data.openid) {
              wx.setStorageSync('openid', res.data.openid);
              console.log('openid已存储:', res.data.openid);
            } else {
              console.error('登录接口返回的openid为空');
            }
            
            getApp().ports.userIdentity({}).then((userRes) => {
              if (userRes.data) {
                wx.setStorageSync('userId', userRes.data.id);
                if (userRes.data.active_role) {
                  wx.setStorageSync('identity', userRes.data.active_role.title);
                }
              }
            }).catch((error) => {
              console.error('获取用户身份失败:', error);
            });
          }
        }).catch((error) => {
          console.error('登录接口调用失败:', error);
        })
      },
      fail: (error) => {
        console.error('微信登录失败:', error);
      }
    })
  },
  setInfo(obj) {
    var that = this;
    getApp().ports.loginInfo({
      data: {
        encryptedData: obj.encryptedData,
        iv: obj.iv,
        appid: that.globalData.appid,
      },
    }).then((res) => {
      console.log(res, '成功');
    }).catch(() => {
      console.error('出啥错了？');
    });
  },
  setPhone(obj) {
    var that = this;
    console.log(obj)
    // return
    getApp().ports.loginPhone({
      data: {
        encryptedData: obj.encryptedData,
        iv: obj.iv,
        appid: that.globalData.appid,
      },
    }).then((res) => {
      console.log(res, '成功');
    }).catch(() => {
      console.error('出啥错了？');
    });
  },
  globalData: {
    // url: 'https://test.business.vajump.com',
    // url2: 'https://test.account.vajump.com',

    apiRoot: base.apiRoot,
    imageRoot: base.imageRoot,
    appid: wx.getAccountInfoSync().miniProgram.appId,
    taxation: {},
    userInfo: '',
    indexUrl: '',
    color: '#603CBA',
    edition: 'v1',
    active_color: '#603CBA',
    longitude: '113.36199',
    latitude: '23.12463',
    phone: '020-8759 4500',
    login: false,

  },
  ports,


})